package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    //客户端
    Socket socket = null;

    public TcpEchoClient(String serverIP,int serverPort) throws IOException {
        //这里是可以直接传参数的对于 服务器的IP和端口号
        socket = new Socket(serverIP,serverPort);
    }

    public void start() {
        Scanner scanner = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {
            //对其记性包装
            Scanner scanner1 = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);

            while (true) {
                // 1、从控制端进行输入
                String request = scanner.next();

                // 2、从客户端进行传送数据，到服务器进行处理
                writer.println(request);
                writer.flush();

                // 3、从服务器接收处理的数据并打印
                String response = scanner1.next();

                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1",9090);
        tcpEchoClient.start();
    }

}
